package com.yuanjin.activity;

import java.io.File;
import java.util.HashMap;
import java.util.LinkedHashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;
import android.widget.VideoView;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.iflytek.sunflower.FlowerCollector;
import com.yuanjin.R;
import com.yuanjin.util.MediaUtils;
import com.yuanjin.util.MyTimeUtils;
import com.yuanjin.util.NotesDB;

public class Note_AddContent_Activity extends Activity
		implements
			OnClickListener {
	private Button savebtn, deletebtn, btn_img, btn_video, btn_voice,
			btn_alarmclock;
	private EditText ettext;
	private ImageView c_img;
	private VideoView v_video;
	private NotesDB notesDB;
	private SQLiteDatabase dbWriter;
	private File photoFile, videoFile;
	private String val;
	private String timeString;
	private String imageThumbnailPath;
	private String videoThumbnailPath;
	private String setTimeString;
	private String edittextString = "";// 记事本输入框内容
	private LinearLayout ll_hand;
	private LinearLayout ll_voice;
	private PopupWindow popupWindow;

	/************************ 讯飞语音识别 *****************************/
	private static String TAG = Voice_IatDemo.class.getSimpleName();
	// 语音听写对象
	private SpeechRecognizer mIat;
	// 语音听写UI
	private RecognizerDialog mIatDialog;
	// 用HashMap存储听写结果
	private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();

	// private EditText mResultText;
	private Button alarm_start;
	private Toast mToast;
	// 引擎类型
	private String mEngineType = SpeechConstant.TYPE_CLOUD;
	int ret = 0; // 函数调用返回值
	private boolean voice_TimeTag = false;
	private int inFlag = 0;// 第n次返回数据标志。经验证发现每次语音返回了两次一样的数据，所以需要过滤掉第一次

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.fragment_note_addcontent);
		initView();

		// 初始化识别无UI识别对象
		// 使用SpeechRecognizer对象，可根据回调消息自定义界面；
		mIat = SpeechRecognizer.createRecognizer(Note_AddContent_Activity.this,
				mInitListener);

		// 初始化听写Dialog，如果只使用有UI听写功能，无需创建SpeechRecognizer
		// 使用UI听写功能，请根据sdk文件目录下的notice.txt,放置布局文件和图片资源
		mIatDialog = new RecognizerDialog(Note_AddContent_Activity.this,
				mInitListener);

		mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
		// mResultText = ((EditText) findViewById(R.id.iat_text));
		// alarm_start = (Button) findViewById(R.id.alarm_start);
		// alarm_start.setOnClickListener(this);
	}

	private void initView() {
		val = getIntent().getStringExtra("flag");// 获取标志
		savebtn = (Button) findViewById(R.id.save);
		deletebtn = (Button) findViewById(R.id.delete);
		ettext = (EditText) findViewById(R.id.ettext);
		c_img = (ImageView) findViewById(R.id.c_img);
		v_video = (VideoView) findViewById(R.id.c_video);
		btn_img = (Button) findViewById(R.id.btn_img);
		btn_video = (Button) findViewById(R.id.btn_vedio);
		btn_voice = (Button) findViewById(R.id.btn_voice);
		btn_alarmclock = (Button) findViewById(R.id.btn_alarmclock);

		btn_voice.setOnClickListener(this);
		btn_img.setOnClickListener(this);
		btn_video.setOnClickListener(this);
		btn_alarmclock.setOnClickListener(this);
		savebtn.setOnClickListener(this);
		deletebtn.setOnClickListener(this);
		notesDB = new NotesDB(this);
		dbWriter = notesDB.getWritableDatabase();

		// 隐藏图片和视频视图
		c_img.setVisibility(View.GONE);
		v_video.setVisibility(View.GONE);
		timeString = MyTimeUtils.getTime();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1) {
			Bitmap bitmap = BitmapFactory.decodeFile(photoFile
					.getAbsolutePath());
			c_img.setImageBitmap(bitmap);

			/******************** 在另一文件夹中保存缩略图 ************************/
			imageThumbnailPath = Environment.getExternalStorageDirectory()
					.toString() + "/yuanjinImage/" + "thumbnail/";
			File out = new File(imageThumbnailPath);
			if (!out.exists()) {
				out.mkdirs();// 若不存在则创建该文件夹
			}
			imageThumbnailPath = imageThumbnailPath + timeString + ".jpg";
			MediaUtils.saveMediaThumbnail_small(MediaUtils.MyMedia_Image,
					photoFile.toString(), imageThumbnailPath);
			/********************************************/
		}
		if (requestCode == 2) {
			v_video.setVideoURI(Uri.fromFile(videoFile));
			v_video.start();
			/******************** 在另一文件夹中保存缩略图 ************************/
			videoThumbnailPath = Environment.getExternalStorageDirectory()
					.toString() + "/yuanjinImage/" + "thumbnail/";
			File out = new File(videoThumbnailPath);
			if (!out.exists()) {
				out.mkdirs();// 若不存在则创建该文件夹
			}
			videoThumbnailPath = videoThumbnailPath + timeString + ".jpg";
			MediaUtils.saveMediaThumbnail_small(MediaUtils.MyMedia_Video,
					videoFile.toString(), videoThumbnailPath);

			/********************************************/
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.save :// 保存

				addDB();
				finish();
				break;

			case R.id.delete :// 取消
				finish();
				break;

			case R.id.btn_alarmclock :// 设置闹钟
				showPopupWindow(v);
				break;
			case R.id.ll_voice :// 设置提醒时间-语音输入
				showSetTimeDialog();
				popupWindow.dismiss();

				break;
			case R.id.ll_hand :// 设置提醒时间-手动设置
				break;
			case R.id.btn_img :// 拍照
				c_img.setVisibility(View.VISIBLE);
				v_video.setVisibility(View.GONE);
				Intent iimg = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 调用摄像头拍照

				/******************************************/
				String imagePathString = Environment
						.getExternalStorageDirectory().toString()
						+ "/yuanjinImage/";// 存放照片的文件夹
				// String fileName=TimeUtils.getTime()+".jpg";
				File out = new File(imagePathString);
				if (!out.exists()) {
					out.mkdirs();
				}
				// photoFile=new File(imagePathString, fileName);
				/******************************************/
				timeString = MyTimeUtils.getTime();
				photoFile = new File(Environment.getExternalStorageDirectory()
						.getAbsoluteFile()
						+ "/yuanjinImage/"
						+ timeString
						+ ".jpg");

				iimg.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));// 另存图片地址
				startActivityForResult(iimg, 1);

				break;
			case R.id.btn_vedio :// 拍摄视频
				c_img.setVisibility(View.GONE);
				v_video.setVisibility(View.VISIBLE);
				timeString = MyTimeUtils.getTime();
				Intent video = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
				videoFile = new File(Environment.getExternalStorageDirectory()
						.toString() + "/yuanjinImage/" + timeString + ".mp4");
				video.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(videoFile));
				startActivityForResult(video, 2);
				break;

			case R.id.btn_voice :// 语音识别
				// edittextString=ettext.getText().toString();
				ettext.setText(edittextString);// 清空显示内容
				mIatResults.clear();
				// 设置参数
				setParam();

				// 显示听写对话框
				mIatDialog.setListener(mRecognizerDialogListener);
				mIatDialog.show();
				showTip(getString(R.string.text_begin));
				break;
		}
	}

	public void addDB() {
		Log.e("test", "进入保存了");
		ContentValues cv = new ContentValues();
		cv.put(NotesDB.CONTENT, ettext.getText().toString());
		cv.put(NotesDB.TIME, timeString);
		cv.put(NotesDB.PATH, photoFile + "");
		cv.put(NotesDB.VIDEO, videoFile + "");
		cv.put(NotesDB.PATH_THUMBNAIL, imageThumbnailPath + "");
		cv.put(NotesDB.VIDEO_THUMBNAIL, videoThumbnailPath + "");
		dbWriter.insert(NotesDB.TABLE_NAME, null, cv);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}

	/**
	 * 初始化监听器。
	 */
	private InitListener mInitListener = new InitListener() {

		@Override
		public void onInit(int code) {
			Log.d(TAG, "SpeechRecognizer init() code = " + code);
			if (code != ErrorCode.SUCCESS) {
				showTip("初始化失败，错误码：" + code);
			}
		}
	};
	/**
	 * 听写UI监听器
	 */
	private RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {
		public void onResult(RecognizerResult results, boolean isLast) {
			printResult(results);
		}

		/**
		 * 识别回调错误.
		 */
		public void onError(SpeechError error) {
			showTip(error.getPlainDescription(true));
		}

	};

	private void printResult(RecognizerResult results) {
		String text = Voice_JsonParser
				.parseIatResult(results.getResultString());

		String sn = null;
		// 读取json结果中的sn字段
		try {
			JSONObject resultJson = new JSONObject(results.getResultString());
			sn = resultJson.optString("sn");
		} catch (JSONException e) {
			e.printStackTrace();
		}

		mIatResults.put(sn, text);

		StringBuffer resultBuffer = new StringBuffer();
		for (String key : mIatResults.keySet()) {
			resultBuffer.append(mIatResults.get(key));
		}

		inFlag++;
		if (inFlag % 2 == 0) {
			if (voice_TimeTag) {// 判断是否为语音设定时间
				setTimeString = resultBuffer.toString();
				Message msg = new Message();
				msg.what = 4;
				mhanler.sendMessage(msg);

			} else {

				edittextString = ettext.getText().toString();
				Log.e("test", "进入了。。。。。。。。。。。。。。。。。。");
				edittextString = edittextString + resultBuffer.toString();
				ettext.setText(edittextString);
				ettext.setSelection(ettext.length());
			}
			inFlag = 0;// 重置为0
		}

	}

	private void showTip(final String str) {
		mToast.setText(str);
		mToast.show();
	}

	/**
	 * 参数设置
	 * 
	 * @param param
	 * @return
	 */
	public void setParam() {
		// 清空参数
		mIat.setParameter(SpeechConstant.PARAMS, null);

		// 设置听写引擎
		mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
		// 设置返回结果格式
		mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");

		// String lag = mSharedPreferences.getString("iat_language_preference",
		// "mandarin");
		String lag = "mandarin";
		if (lag.equals("en_us")) {
			// 设置语言
			mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
		} else {
			// 设置语言
			mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
			// 设置语言区域
			mIat.setParameter(SpeechConstant.ACCENT, lag);
		}

		// 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
		mIat.setParameter(SpeechConstant.VAD_BOS, "4000");

		// 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
		mIat.setParameter(SpeechConstant.VAD_EOS, "1000");

		// 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
		mIat.setParameter(SpeechConstant.ASR_PTT, "1");

		// 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
		// 注：AUDIO_FORMAT参数语记需要更新版本才能生效
		mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
		mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH,
				Environment.getExternalStorageDirectory() + "/msc/iat.wav");

		// 设置听写结果是否结果动态修正，为“1”则在听写过程中动态递增地返回结果，否则只在听写结束之后返回最终结果
		// 注：该参数暂时只对在线听写有效
		mIat.setParameter(SpeechConstant.ASR_DWA, "0");
	}

	private void showSetTimeDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("下一步~");
		builder.setMessage("语音输入提醒时间-->支持格式：xxxx年xx月xx日xx时xx分 或 xx月xx日xx时xx分");
		builder.setPositiveButton("设置提醒时间",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						voice_TimeTag = true;
						Message msg = new Message();
						msg.what = 1;
						mhanler.sendMessage(msg);
						dialog.dismiss();

					}
				});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// mp.stop();
				dialog.dismiss();
				voice_TimeTag=false;
			}
		});
		builder.setCancelable(false);
		builder.show();

	}

	private void showConfirmSetTimeDialog() {
		String showString = "您设定的时间为：";
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("提醒时间确认");
		builder.setMessage(showString + setTimeString);
		builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Message msg = new Message();
				msg.what = 3;
				mhanler.sendMessage(msg);
				dialog.dismiss();
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// mp.stop();
				dialog.dismiss();
			}
		});
		builder.setCancelable(false);
		builder.show();
	}

	public void showPopupWindow(View view) {
		// 自定义一个布局，作为显示时的布局
		View popupview = this.getLayoutInflater().inflate(
				R.layout.popupwindow_notebook, null);
		// 设置popupview中按钮的点击事件
		ll_hand = (LinearLayout) popupview.findViewById(R.id.ll_hand);
		ll_voice = (LinearLayout) popupview.findViewById(R.id.ll_voice);
		ll_hand.setOnClickListener(Note_AddContent_Activity.this);
		ll_voice.setOnClickListener(Note_AddContent_Activity.this);
		popupWindow = new PopupWindow(popupview, LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT, true);
		popupWindow.setTouchable(true);
		popupWindow.setTouchInterceptor(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				Log.e(Note_AddContent_Activity.class.getSimpleName(), "ontouch");
				return false;
				// 如果返回true的话，touch事件将会被拦截
				// 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
			}
		});
		// 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
		// 我觉得这里是API的一个bug

		popupWindow.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.ic_launcher));

		// 获得view在视图中的坐标
		int[] location = new int[2];
		view.getLocationOnScreen(location);
		popupview.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		// Log.e(MyActivity.class.getSimpleName(), "getMeasuredHeight= "
		// + popupview.getMeasuredHeight() + "   getMeasuredWidth= "
		// + popupview.getMeasuredWidth());
		popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, location[0],
				location[1] - popupview.getMeasuredHeight() - 20);

	}

	Handler mhanler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case 1 :// 语音输入提醒时间
						// 显示听写对话框
					mIatDialog.setListener(mRecognizerDialogListener);
					mIatDialog.show();
					showTip(getString(R.string.text_begin));
					break;
				case 2 :// 继续编辑输入
						// 显示听写对话框
					mIatDialog.setListener(mRecognizerDialogListener);
					mIatDialog.show();
					showTip(getString(R.string.text_begin));
					break;
				case 3 :// 设定闹钟时间
						// 显示听写对话框
						// 启动闹钟
					String editTime = setTimeString;
					String timeFormat = "yyyy年MM月dd日HH时mm分";
					// 修正语音获取的日期格式
					editTime = MyTimeUtils.TimeCheck(editTime);
					Log.e("test", "修正后的时间为： "+editTime);
					Log.e("test", "修正后的时间为： "+editTime);
					Log.e("test", "修正后的时间为： "+editTime);
					// 获取设定日期对应的毫秒数
					long triggerAtMillis = MyTimeUtils.getTimeFromString(
							editTime, timeFormat);// 闹铃时间

					AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
					Intent intent = new Intent(Note_AddContent_Activity.this,
							AlarmActivity.class);
					PendingIntent op = PendingIntent.getActivity(
							Note_AddContent_Activity.this, 0, intent,
							PendingIntent.FLAG_UPDATE_CURRENT);
					am.set(AlarmManager.RTC_WAKEUP, triggerAtMillis, op);

					break;
				case 4 :// 语音设定时间
					showConfirmSetTimeDialog();
					voice_TimeTag = false;// 重置
					break;
				case 5 :

					break;
				default :
					break;
			}
		};
	};

	@Override
	protected void onResume() {
		// 开放统计 移动数据统计分析
		FlowerCollector.onResume(Note_AddContent_Activity.this);
		FlowerCollector.onPageStart(TAG);
		super.onResume();
	}

	@Override
	protected void onPause() {
		// 开放统计 移动数据统计分析
		FlowerCollector.onPageEnd(TAG);
		FlowerCollector.onPause(Note_AddContent_Activity.this);
		super.onPause();
	}
}
